package com.suixun.service.credits.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.authority.common.MD5Util;
import com.suixun.dao.CompanyUserMapper;
import com.suixun.dao.credits.CompanyUserDao;
import com.suixun.entity.credits.CompanyUser;
import com.suixun.entity.credits.CompanyUserExample;
import com.suixun.service.credits.CompanyUserService;

/**
 * 商户账号管理
 * 
 * @author yh
 * @date 2017年12月11日
 */
@Service
public class CompanyUserServiceImpl implements CompanyUserService {

    @Autowired
    private CompanyUserMapper companyUserMapper;
    
    @Autowired
    private CompanyUserDao companyUserDao;

    @Override
    @Transactional
    public void insert(CompanyUser user) {
        user.setId(null);
        user.setStatus((short) 1);
        user.setCreateTime(new Date());
        user.setPwd(MD5Util.MD5(user.getAccount()));
        companyUserMapper.insert(user);
    }

    @Override
    @Transactional
    public void update(CompanyUser user) {
        if (user.getId() != null) {
            user.setPwd(null);
            user.setCreateTime(new Date());
            companyUserMapper.updateByPrimaryKeySelective(user);
        }
    }
    
    @Override
    public CompanyUser findByAccount(String account) {
        CompanyUserExample userExample = new CompanyUserExample();
        userExample.createCriteria().andAccountEqualTo(account);
        List<CompanyUser> list = companyUserMapper.selectByExample(userExample);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }
    
    @Override
    public CompanyUser findByCompanyid(Integer companyid) {
        return companyUserDao.findByCompanyid(companyid);
    }
    
    @Override
    public boolean verifyAccount(String account, Integer companyid) {
        CompanyUser user = findByAccount(account);
        if (user == null) {
            return true;
        }
        // 修改时的校验
        if (companyid != null && companyid > 1) {
            CompanyUser olduser = findByCompanyid(companyid);
            if(olduser == null){
                return false;
            }
            if (user.getId().equals(olduser.getId())) {
                return true;
            }
        }
        return false;
    }

}
